/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bd2_xml.persistencia;

import bd2_xml.visual.Principal;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author comp1
 */
public class Conexao {

    public static Connection getConnection() throws IOException {
        
        Connection con = null;
        try {
            Class.forName("org.hsqldb.jdbcDriver");
            con = DriverManager.getConnection("jdbc:hsqldb:hsql://"+Principal.TFNomeBanco.getText(), "SA", "");
            System.out.println("Conexao com o banco realizada com sucesso!");
        } catch (ClassNotFoundException e) {
            System.out.println("Erro de classe da Conexão nao encontrada");
            e.printStackTrace();
        } catch (SQLException e) {
            StringBuilder s = new StringBuilder();
            s.append("Log erro:");
            s.append(System.lineSeparator());
            StackTraceElement[] elemento = e.getStackTrace();
            for (int i = elemento.length - 1; i > 0; i--) {
                s.append(elemento[i].toString());
                s.append(System.lineSeparator());
            }
            System.out.println(s.toString());
            RandomAccessFile saida = null;
            try {
                JOptionPane.showMessageDialog(null, "Erro de Conexão do banco:\n"
                        + "Favor verificar log.txt", "Conexão Banco", 0);
                File arquivo = new File("log.txt");
                saida = new RandomAccessFile(arquivo, "rw");
                saida.writeUTF(s.toString());
                System.exit(-1);
            } catch (IOException ex) {
                Logger.getLogger(Conexao.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                saida.close();
            }
        }
        return con;
    }
}
